package com.example.blog.controller;

import com.example.blog.common.R;
import com.example.blog.dao.ArticleDAO;
import com.example.blog.dao.CommentDAO;
import com.example.blog.dao.UserDAO;
import com.example.blog.dto.ArticleDTO;
import com.example.blog.model.Article;
import com.example.blog.model.Comment;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("article")
public class ArticleController {
    @Resource
    public ArticleDAO articleDAO;
    @Resource
    public UserDAO userDAO;
    @Resource
    public CommentDAO commentDAO;

    @GetMapping("list")
    public Object list(@RequestParam int id) {
        List<Article> articles;

        if (id == 0) {
            articles = articleDAO.findAll();
        } else {
            articles = articleDAO.findAllByUserId(id);
        }
        return R.success(articles);
    }

    @GetMapping("detail")
    public Object detail(@RequestParam int id, @RequestParam int userId) {
        HashMap<Object, Object> map = new HashMap<>();
        Article article = articleDAO.findById(id).get();
        map.put("article", article);
        map.put("isAuthor", article.user.id == userId);
        List<Comment> comments= commentDAO.findAllByArticle(article);
        map.put("comments",comments );
        return R.success(map);
    }

    @DeleteMapping("delete")
    public Object delete(@RequestParam int id) {
        articleDAO.deleteById(id);
        return R.success();
    }

    @PostMapping("post")
    public Object post(@RequestBody ArticleDTO articleDTO) {
        Article article;
        if (articleDTO.id == 0) {
            article = new Article(articleDTO.title, articleDTO.description, articleDTO.content);
            System.out.println(articleDTO.userId);
            article.user = userDAO.findById(articleDTO.userId).get();
        } else {
            article = articleDAO.findById(articleDTO.id).get();
            article.title = articleDTO.title;
            article.description = articleDTO.description;
            article.content = articleDTO.content;
        }
        article.lastEditTime = new Date();
        articleDAO.save(article);

        HashMap<Object, Object> map = new HashMap<>();
        map.put("id", article.id);
        return R.success(map);
    }
}
